<template>
  <div class="rapid-authorization">
    <div class="content">
      <div class="party">
        <div class="right">
          数据权限：
          <je-select
            v-model:value="selectValue"
            :options="options"
            :allow-clear="false"
          ></je-select>
        </div>
        <div class="tip"
          >说明：当您开启数据权限后，系统默认控制：本人只能查看、修改、删除本人录入的数据。若您需要更多用户查看及操作数据，请开启下列数据权限。</div
        >
      </div>
      <div class="items">
        <ListItem
          v-for="item in JE_DATAAUTHORITY_ITEMLIST1"
          :key="item.id"
          v-model:res="item.value"
          :label="item.title"
          :disable="item.disabled"
          :info="item.info"
          :index="item.id"
          @listItemChange="listItemChange"
        />
        <TreeSelectItem
          v-for="item in JE_DATAAUTHORITY_TREESELECTDATA1"
          :key="item.id"
          :label="item.title"
          :disable="item.disabled"
          :info="item.info"
          :index="item.id"
          :config="item.config"
          :res="item.ids"
          :texts="item.texts"
          @selectItemChange="selectItemChange"
          @selectConfigChange="selectConfigChange"
        />
      </div>
    </div>
    <div class="footer">
      <je-button type="primary" :disabled="btnDisabled" class="btn" @click="save"
        >保存刷新</je-button
      >
      <je-button class="btn" :disabled="disabled || btnDisabled" @click="reset">恢复数据</je-button>
      <je-button class="btn" @click="closeEvent">关闭</je-button>
    </div>
  </div>
</template>

<script>
  import {
    defineAsyncComponent,
    defineComponent,
    onMounted,
    reactive,
    ref,
    toRefs,
    watch,
  } from 'vue';

  import { Button, Modal, Select } from '@jecloud/ui';

  import {
    JE_DATAAUTHORITY_CONFIGDATA,
    JE_DATAAUTHORITY_ITEMLIST,
    JE_DATAAUTHORITY_RAPAYLOADDATA,
    JE_DATAAUTHORITY_RAPAYLOADMETADATA,
    JE_DATAAUTHORITY_RASQLOOPTIONS,
    JE_DATAAUTHORITY_TREESELECTDATA,
  } from '@/helper/constant';

  import { doSaveApi, getPremDataApi } from '@/api/authorization';

  import { useDialog } from '@/hooks/use-dialog';

  import VueEvent from '@/helper/model/event';

  export default defineComponent({
    name: 'RapidAuthorization',
    components: {
      ListItem: defineAsyncComponent(() => import('./list-litem.vue')),
      TreeSelectItem: defineAsyncComponent(() => import('./tree-select-item.vue')),
      JeButton: Button,
      JeSelect: Select,
    },
    props: {
      currentFuncId: {
        type: String,
        default: '',
      },
      currentFuncCode: {
        type: String,
        default: '',
      },
      parentModal: String,
    },
    emits: ['isChange'],
    setup(props, { emit }) {
      // 下拉选项
      const options = ref(JE_DATAAUTHORITY_RASQLOOPTIONS);
      // 下拉值
      const selectValue = ref('0');
      const JE_DATAAUTHORITY_ITEMLIST1 = JSON.parse(JSON.stringify(JE_DATAAUTHORITY_ITEMLIST));
      const JE_DATAAUTHORITY_TREESELECTDATA1 = JSON.parse(
        JSON.stringify(JE_DATAAUTHORITY_TREESELECTDATA),
      );

      // 页面所有数据
      // const allData = ref([]);
      // 传参
      const payloadData = ref(JE_DATAAUTHORITY_RAPAYLOADDATA);
      let meta = JE_DATAAUTHORITY_RAPAYLOADMETADATA; //对比项
      let metaOpen = ref('0');
      const btnDisabled = ref(false); // 按钮禁用
      const disabled = ref(true); // 按钮禁用

      // 设置对象
      const config = JE_DATAAUTHORITY_CONFIGDATA;
      const listArr = [];
      // list 选择变换
      const listItemChange = (id, result) => {
        if (!listArr.includes(id)) {
          // 不存在且result === '1'，加入数组
          if (result === '1') {
            listArr.push(id);
          }
        } else {
          // 存在且result === '0'，从数组删除
          if (result === '0') {
            let _index = listArr.indexOf(id);
            listArr.splice(_index, 1);
          }
        }
        // selectPermStr转化成字符串
        payloadData.value.selectPermStr = listArr.join(',');
      };
      // tree型选择器变化
      const selectItemChange = (_index, formState) => {
        // 不存在_indexz不再继续
        if (!_index) return false;
        // 存在formState.ids
        if (formState.ids) {
          // 赋值
          payloadData.value[_index].ids = JSON.parse(JSON.stringify(formState.ids));
          payloadData.value[_index].texts = JSON.parse(JSON.stringify(formState.texts));
        } else {
          // 否则置空
          payloadData.value[_index].ids = '';
          payloadData.value[_index].texts = '';
        }
      };
      // tree型选择器配置变化
      const selectConfigChange = (index, result) => {
        const res = [];
        result.forEach((item, e) => {
          if (config[index][result[e]]) {
            res[e] = config[index][result[e]];
          }
        });
        // 转化成字符串
        payloadData.value[index].configPerm = res.join(',');
      };

      // 保存
      const save = () => {
        // 数据发生变化才进行操作
        if (isChange()) return Modal.notice('无数据操作!', 'info');
        btnDisabled.value = true;
        // 调用保存接口
        doSaveApi({
          tableCode: 'JE_CORE_FUNCPERM',
          FUNCPERM_FUNCINFO_CODE: funcCode.value,
          FUNCPERM_FUNCINFO_ID: funcId.value,
          FUNCPERM_TYPE: 'fastAuth',
          FUNCPERM_ON_OFF: selectValue.value,
          FUNCPERM_CONFIG: JSON.stringify(payloadData.value),
        }).then((res) => {
          Modal.notice(res.message, 'success');
          btnDisabled.value = false;
          // 对照组重新赋值
          meta = JSON.parse(JSON.stringify(payloadData.value));
          metaOpen.value = JSON.parse(JSON.stringify(selectValue.value));
        });
      };

      const funcId = ref('');
      const funcCode = ref('');
      onMounted(() => {
        initData();
      });

      // 初始化数据
      const initData = () => {
        // 接收传入的id和code
        funcId.value = props.currentFuncId;
        funcCode.value = props.currentFuncCode;
        // 获取页面数据
        if (!funcId.value) return false;
        btnDisabled.value = true;
        // 调用得到初始数据接口
        getPremDataApi({
          tableCode: 'JE_CORE_FUNCPERM',
          FUNCPERM_FUNCINFO_ID: funcId.value,
          FUNCPERM_TYPE: 'fastAuth',
        }).then((res) => {
          btnDisabled.value = false;
          if (res.length > 0) {
            selectValue.value = res[0]?.values?.FUNCPERM_ON_OFF || '0';
            // 对照组赋值
            metaOpen.value = JSON.parse(JSON.stringify(selectValue.value));
            const res1 = res[0]?.values?.FUNCPERM_CONFIG;
            if (res[0]?.values?.FUNCPERM_CONFIG) {
              // 数据赋值
              payloadData.value = JSON.parse(JSON.stringify(JSON.parse(res1)));
            }
            // selectPermStrData转换成数组赋值
            const selectPermStrData = payloadData.value.selectPermStr.split(',');
            state.JE_DATAAUTHORITY_ITEMLIST1.forEach((item) => {
              // 1代表存在即是勾选状态
              if (selectPermStrData.includes(item.id)) {
                item.value = '1';
              }
            });
            // 此处是给树形选择赋值：ids和texts
            state.JE_DATAAUTHORITY_TREESELECTDATA1.forEach((item) => {
              if (res[0]?.values?.FUNCPERM_CONFIG) {
                item.texts = JSON.parse(res[0]?.values?.FUNCPERM_CONFIG)[item.id]?.texts;
                item.ids = JSON.parse(res[0]?.values?.FUNCPERM_CONFIG)[item.id]?.ids;
              }
              // 配置赋值
              item.config = payloadData.value[item.id]?.configPerm;
            });
            // 子组件重新load数据
            VueEvent.emit('setValue');
            // 修改对照组
            meta = JSON.parse(JSON.stringify(payloadData.value));
          }
        });
      };

      const state = reactive({
        JE_DATAAUTHORITY_ITEMLIST1, // 快速授权list数据
        JE_DATAAUTHORITY_TREESELECTDATA1, // 快速授权tree选择数据
      });

      // 监听selectValue的值，控制页面的禁用状态
      watch(
        () => selectValue.value,
        (nv) => {
          state.JE_DATAAUTHORITY_ITEMLIST1.forEach((item) => {
            item.disabled = nv === '0';
          });
          disabled.value = nv === '0';
          state.JE_DATAAUTHORITY_TREESELECTDATA1.forEach((item) => {
            item.disabled = nv === '0';
          });
        },
        { immediate: true },
      );

      // 对比是否的改变
      const isChange = () => {
        // 当前数据和对照组的每一项一致才返回为真
        const bol = Object.keys(meta).every((item) => {
          if (item === 'selectPermStr') {
            return meta[item] == payloadData.value[item];
          } else {
            return (
              meta[item].texts === payloadData.value[item].texts &&
              meta[item].configPerm === payloadData.value[item].configPerm
            );
          }
        });
        const isTrue = metaOpen.value == selectValue.value;
        return bol && isTrue;
      };

      // 恢复数据
      const reset = () => {
        Modal.confirm('您确定要恢复数据吗？', () => {
          toReset();
        });
      };

      // 回退数据
      const toReset = () => {
        const selectPermStrData =
          meta.selectPermStr && JSON.parse(JSON.stringify(meta.selectPermStr.split(',')));
        // 回退列表数据
        state.JE_DATAAUTHORITY_ITEMLIST1.forEach((item) => {
          if (selectPermStrData?.includes(item.id)) {
            item.value = '1';
          }
        });
        // 回退tree型选择器数据
        state.JE_DATAAUTHORITY_TREESELECTDATA1.forEach((item) => {
          item.texts = meta[item.id]?.texts && JSON.parse(JSON.stringify(meta[item.id]?.texts));
          item.ids = meta[item.id]?.ids && JSON.parse(JSON.stringify(meta[item.id]?.ids));
          item.config =
            meta[item.id]?.configPerm && JSON.parse(JSON.stringify(meta[item.id]?.configPerm));
        });
        // 回禁用开关数据
        selectValue.value = JSON.parse(JSON.stringify(metaOpen.value));
        // 更新子组件视图
        VueEvent.emit('setValue');
      };

      // 切换tab的回调
      const changeTabCb = () => {
        const flag = isChange();
        if (flag) return emit('isChange', flag);
        // 弹框
        useDialog({ toReset, save, isDicOrRole: false });
      };

      // 关闭
      const closeEvent = () => {
        props.parentModal.close();
      };

      return {
        options,
        selectValue,
        funcId,
        funcCode,
        btnDisabled,
        disabled,
        ...toRefs(state),
        listItemChange,
        selectItemChange,
        selectConfigChange,
        save,
        reset,
        closeEvent,
        changeTabCb,
      };
    },
  });
</script>

<style lang="less" scoped>
  .rapid-authorization {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100%;
    padding: 0 20px;
    border: 1px solid #d7d7d7;
    background: #edf0f4;
    .footer {
      height: 0px;
      min-height: 70px;
      .btn {
        margin-right: 15px;
        margin-top: 20px;
      }
    }
    .content {
      flex: '1';
      overflow-y: auto;
      &::-webkit-scrollbar {
        display: none;
      }
      width: 100%;
      .party {
        margin-top: 20px;
        padding-left: 16px;
        width: 100%;
        height: 50px;
        background: #ffffff;
        line-height: 50px;
        display: flex;
      }
      .tip {
        margin-left: 8px;
        font-size: 13px;
        color: #a9aba9;
      }
      .right {
        min-width: 200px;
      }
      :deep(.items) {
        .list-item:nth-of-type(2n) {
          margin-left: 1%;
        }
        .tree-select-item:nth-of-type(2n) {
          margin-left: 1%;
        }
      }
    }
  }
</style>
